#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
import mrget
import pycdlib
import chardet
from .._util import Util
from .._const import Arch, Version, Edition, Lang
from .._prototype import WindowsInstallationMediaBase
from .._errors import InstallMediaError


class LocalInstallationMedia(WindowsInstallationMediaBase):

    def __init__(self, iso_filepath, boot_floppy_filepath, no_pnp_bios_filepath, patcher9x_floppy_filepath, simd95_filepath=None, driverpack_filepath_dict={}):
        super().__init__()

        self._isoPath = iso_filepath
        self._bootFloppyPath = boot_floppy_filepath
        self._noPnpBiosPath = no_pnp_bios_filepath
        self._patcher9xFloppyPath = patcher9x_floppy_filepath
        self._simd95Path = simd95_filepath
        self._driverPackPathDict = driverpack_filepath_dict

        iso = pycdlib.PyCdlib()
        iso.open(iso_filepath)
        try:
            if len(iso.pvds) != 1:
                raise InstallMediaError("invalid ISO file, multiple PVDs")
            if iso.has_rock_ridge():
                raise InstallMediaError("invalid ISO file, Microsoft does not use Rock Ridge extension")
            if not iso.has_joliet():
                raise InstallMediaError("invalid ISO file, Microsoft Windows 98 uses Joilet extension")

            self._arch = Arch.X86

            self._version = Version.WINDOWS_98

            # use label and file version in SETUP.EXE to detect edition
            label = Util.pycdlibGetLabel(iso)
            buf = Util.pycdlibReadBinaryFile(iso, iso_path="/SETUP.EXE")
            if label == "WIN98" and b'FileVersion\0' + b'4.10.1998\0' in buf:
                edition = Edition.WINDOWS_98
            elif label == "WIN98 SE" and b'FileVersion\0' + b'4.10.2222\0' in buf:
                edition = Edition.WINDOWS_98_SE
            else:
                raise InstallMediaError("invalid ISO file, unknown edition")
            self._editions = [edition]

            # use README.TXT to detect language
            buf = Util.pycdlibReadBinaryFile(iso, iso_path="/README.TXT")
            ret = chardet.detect(buf)
            if ret['encoding'] == "ascii":
                lang = Lang.en_US
            elif ret['encoding'] == "big5":
                lang = Lang.zh_TW
            else:
                print(ret['encoding'])      # FIXME
                raise InstallMediaError("invalid ISO file, unknown language")
            self._languages = [lang]

            # this is the only difference between Retail and OEM
            buf = Util.pycdlibReadBinaryFile(iso, iso_path="/WIN98/PRECOPY2.CAB")
            chksum = Util.generateSha256(buf)
            if edition == Edition.WINDOWS_98_SE:
                if lang == Lang.en_US:
                    if chksum == "e4079964b124a0455afd17dfad77924fd73350e700b9599f89690626f66e94db":
                        oem = False
                    elif chksum == "a52d6e1fad1b85aef3e0eba4ed1d35a8b982cc572fdcb358fba09b2ce282af81":
                        oem = True
                    else:
                        assert False
                else:
                    assert False
            else:
                assert False
            self._oem = oem

            # boot floppy
            if Util.pycdlibHasEltorito(iso):
                assert self._bootFloppyPath is None
            else:
                assert self._bootFloppyPath is not None
        finally:
            iso.close()

    def is_retail_or_oem(self):
        return not self._oem

    def get_iso_filepath(self):
        return self._isoPath

    def get_boot_floppy_filepath(self):
        return self._bootFloppyPath

    def get_no_pnp_bios_filepath(self):
        return self._noPnpBiosPath

    def get_patcher9x_floppy_filepath(self):
        return self._patcher9xFloppyPath

    def get_simd95_filepath(self):
        return self._simd95Path

    def get_driverpack_filepath_dict(self):
        return self._driverPackPathDict


class CloudInstallationMedia(WindowsInstallationMediaBase):

    def __init__(self, arch, version, edition, lang, retail_or_oem, local_iso_filepath=None, local_boot_floppy_filepath=None, local_no_pnp_bios_filepath=None, local_patcher9x_floppy_filepath=None, local_simd95_filepath=None):
        assert arch == Arch.X86
        assert version == Version.WINDOWS_98
        assert edition in [Edition.WINDOWS_98, Edition.WINDOWS_98_SE]

        super().__init__()

        self._arch = arch
        self._version = version
        self._editions = [edition]
        self._languages = [lang]
        self._retail = retail_or_oem

        self._isoPath = local_iso_filepath
        self._noPnpBiosPath = local_no_pnp_bios_filepath
        self._bootFloppyPath = local_boot_floppy_filepath
        self._patcher9xFloppyPath = local_patcher9x_floppy_filepath
        self._simd95Path = local_simd95_filepath

        self._bDownloaded = False

    def is_retail_or_oem(self):
        return self._retail

    def download(self):
        baseUrl = mrget.target_urls("mirror://oldwin", filter_key=lambda x: x["protocol"] in ["http", "https", "ftp"])[0]

        if self._editions[0] == Edition.WINDOWS_98_SE:
            if self._languages[0] == Lang.en_US:
                if self._retail:
                    isoUrl = os.path.join(baseUrl, "windows-98-se.en-us.iso")
                    bootFloppyUrl = os.path.join(baseUrl, "Windows_98_Second_Edition_Boot.ima")
                else:
                    isoUrl = os.path.join(baseUrl, "windows-98-se-oem.en-us.iso")
                    bootFloppyUrl = None
            else:
                assert False
        else:
            assert False

        if isoUrl is not None:
            assert self._isoPath is not None
            Util.wgetDownload(isoUrl, self._isoPath)

        if bootFloppyUrl is not None:
            assert self._bootFloppyPath is not None
            Util.wgetDownload(bootFloppyUrl, self._bootFloppyPath)

        if True:
            assert self._noPnpBiosPath is not None
            url = "https://files.emulace.cz/seabios-qemu.zip"
            Util.wgetDownloadAndExtractZipFiles(url, {"bios.bin": self._noPnpBiosPath})     # from https://github.com/JHRobotics/softgpu/blob/main/README.md

        if True:
            assert self._patcher9xFloppyPath is not None
            url = mrget.target_urls("mirror://github/JHRobotics/patcher9x/releases/download/v0.8.50/patcher9x-0.8.50-boot.ima")[0]
            Util.wgetDownload(url, self._patcher9xFloppyPath)

        if True:
            assert self._simd95Path is not None
            url = mrget.target_urls("mirror://github/JHRobotics/simd95/releases/download/v1.0/simd95-v1.0.zip")[0]
            Util.wgetDownloadAndExtractZipFiles(url, {"simd95.com": self._simd95Path})

        self._bDownloaded = True

    def get_iso_filepath(self):
        assert self._bDownloaded
        return self._isoPath

    def get_boot_floppy_filepath(self):
        assert self._bDownloaded
        return self._bootFloppyPath

    def get_no_pnp_bios_filepath(self):
        assert self._bDownloaded
        return self._noPnpBiosPath

    def get_patcher9x_floppy_filepath(self):
        assert self._bDownloaded
        return self._patcher9xFloppyPath

    def get_simd95_filepath(self):
        assert self._bDownloaded
        return self._simd95Path

    def get_driverpack_filepath_dict(self):
        # FIXME
        return {}
